/**
 * 可外部配置的路由定义适配器
 * 根据业务事件响应跳转对应路由地址
 */
import Navigo from 'navigo';
import EventBus from '@lib/ebus';
import { search2obj } from '@lib/string';
import routerMap from './map';

export const events = new EventBus();
export const router: any = new Navigo(null, true);

const handler = (params, query) => {
  // 关联的组件
  let component: any = {};
  // 标题
  let title = '';
  // 首页特殊指定
  if (!params) params = { container: 'home' };
  if (routerMap[params.container]) {
    component.container = routerMap[params.container];
  }
  if (params.func && routerMap[`${params.container}.${params.func}`]) {
    component.func = routerMap[`${params.container}.${params.func}`];
  }
  if (
    params.action &&
    routerMap[`${params.container}.${params.func}.${params.action}`]
  ) {
    component.action = routerMap[`${params.container}.${params.func}.${params.action}`];
  }
  events.emit('match', {
    component,
    params,
    query: search2obj(query)
  });
  console.log('路由:', component, params, search2obj(query));
};

router.on({
  '/': handler,
  '/:container': handler,
  '/:container/:func': handler,
  '/:container/:func/:action': handler
});

router.push = (mapName, query={}) => {
  if (routerMap[mapName]) {
    router.navigate(routerMap[mapName].url);
  }
}